//
//  ViewController.m
//  FDSMeshLibDemo
//
//  Created by LEIPENG on 2022/5/17.
//

#import "ViewController.h"
#import "GroupViewController.h"
#import "NodeViewController.h"
#import "SettingViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) MeshTool *meshTool;
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *createButton;

@end

@implementation ViewController

#pragma mark - Initialize
- (void)InitializeCode{
    self.title = @"Studio";
    self.meshTool = [MeshTool shareInstance];
    self.createButton.layer.cornerRadius = 22;
    self.createButton.layer.masksToBounds = YES;
    // 配置弹窗
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
    [SVProgressHUD setMinimumDismissTimeInterval:2.0];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    // 配置菜单
    self.navigationController.navigationBar.tintColor=ColorRGBHex(0x71DADF);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"list_02"] style:(UIBarButtonItemStylePlain) target:self action:@selector(clickSettingItem)];
    self.navigationItem.rightBarButtonItem = rightItem;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMoving:)];
    [self.tableview addGestureRecognizer:longPress];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}

#pragma mark - UILongPressGestureRecognizer
- (void)longPressMoving:(UILongPressGestureRecognizer *)longPress{
    if (UIGestureRecognizerStateBegan == longPress.state) {
        NSIndexPath *selectIndexPath = [self.tableview indexPathForRowAtPoint:[longPress locationInView:self.tableview]];
        if (selectIndexPath.row < self.meshTool.meshModel.studioList.count) {
            __block MeshStudioModel *studioModel = self.meshTool.meshModel.studioList[selectIndexPath.row];
            if (studioModel) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除Stduio？" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
                [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    NSMutableArray *studioList = [NSMutableArray arrayWithArray:self.meshTool.meshModel.studioList];
                    [studioList removeObject:studioModel];
                    self.meshTool.meshModel.studioList = studioList;
                    [self.meshTool codingMeshData:self.meshTool.meshModel];
                    [self.tableview reloadData];
                }]];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
    }
}

#pragma mark - UIButton
- (void)clickSettingItem{
    SettingViewController *viewController = [[SettingViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
}
- (IBAction)clickCreateBtn:(UIButton *)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"新增Stduio？" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        MeshStudioModel *studioModel = [self.meshTool getMeshStudioModel:[NSString stringWithFormat:@"Studio-%ld",(long)(self.meshTool.meshModel.studioList.count+1)]];
        NSMutableArray *studioList = [NSMutableArray arrayWithArray:self.meshTool.meshModel.studioList];
        [studioList addObject:studioModel];
        self.meshTool.meshModel.studioList = studioList;
        [self.meshTool codingMeshData:self.meshTool.meshModel];
        [self.tableview reloadData];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.meshTool.meshModel.studioList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MeshStudioModel *studioModel = self.meshTool.meshModel.studioList[indexPath.row];
    cell.textLabel.text = studioModel.title;
    cell.detailTextLabel.text = @"";
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MeshStudioModel *studioModel = self.meshTool.meshModel.studioList[indexPath.row];
    if (studioModel.meshJson.length) {
        // 加载MESH信息并重启网络
        self.meshTool.studioModel = studioModel;
        
        // 清空过滤
        [FDSMeshApi filterAutoConnectedNode:@[]];
        
        // 导入Studio-Mesh数据 - 有无网络均可
        [self importStudioMeshData:self.meshTool.studioModel.meshJson];
        
        // 导入其它手机分享的Mesh数据 - 必须有网络
        // [self replaceShareMeshJson];
        // [self importShareMeshData:self.meshTool.studioModel.meshJson];
    } else {
        [SVProgressHUD showErrorWithStatus:@"无效的组网信息！"];
    }
}
- (void)presentTabViewController{
    NodeViewController *nodeListCtl = [[NodeViewController alloc] init];
    nodeListCtl.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"节点" image:[UIImage imageNamed:@"list_00"] selectedImage:[[UIImage imageNamed:@"list_01"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    UINavigationController *nodeListNavCtl=[[UINavigationController alloc] initWithRootViewController:nodeListCtl];
    nodeListNavCtl.navigationBar.tintColor=ColorRGBHex(0x71DADF);
    
    GroupViewController *groupListCtl = [[GroupViewController alloc] init];
    groupListCtl.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"组别" image:[UIImage imageNamed:@"list_10"] selectedImage:[[UIImage imageNamed:@"list_11"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    UINavigationController *groupListNavCtl=[[UINavigationController alloc] initWithRootViewController:groupListCtl];
    groupListNavCtl.navigationBar.tintColor=ColorRGBHex(0x71DADF);
    
    UITabBarController *tabBarCtl=[[UITabBarController alloc] init];
    NSArray *viewCtlArr=[NSArray arrayWithObjects:nodeListNavCtl,groupListNavCtl,nil];
    tabBarCtl.viewControllers=viewCtlArr;
    tabBarCtl.selectedIndex=0;
    // tabBarCtl.tabBar.translucent=NO;
    tabBarCtl.tabBar.tintColor = ColorRGBHex(0x71DADF);
    tabBarCtl.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:tabBarCtl animated:YES completion:nil];
}

#pragma mark - 导入Studio-Mesh数据
- (void)importStudioMeshData:(NSString *)meshJson{
    // MESH数据转换
    NSDictionary *meshDic = [MeshTool jsonStringToDic:self.meshTool.studioModel.meshJson];
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        /*
         importMeshJson接口-网络请求无论成功或失败都会导入Mesh数据，超时时间3秒
         切换Studio网络、重复进入相同Studio网络、重启App加载网络等都建议使用以下方法。
         isRequest一般建议都传YES，一些单网络应用或不分享网络的应用isRequest可传NO。
         */
        UInt16 provisionAddress = [FDSMeshApi importMeshJson:meshDic isRequest:YES];
        NSLog(@"provisionAddress ---> %d", provisionAddress);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 保存最新Mesh数据到本地
            self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            
            [SVProgressHUD dismiss];
            [self presentTabViewController];
        });
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [FDSMeshApi refreshWorkNormal];
        });
    });
}

#pragma mark - 导入其它手机分享的Mesh数据
- (void)importShareMeshData:(NSString *)meshJson{
    // Mesh数据转换
    NSDictionary *meshDic = [MeshTool jsonStringToDic:meshJson];
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        /*
         判断是否能够导入Mesh数据
         canImportMeshJson接口-网络请求不成功的情况下，不会导入Mesh数据
         分享导入其它手机的数据建议使用以下方法。isForce 默认传NO，如果传YES则AppUUID会强制修改，后台会重新分配地址。
         */
        NSInteger server_address = 0xFFFF;
        if ([FDSMeshApi canImportMeshJson:meshDic isForce:NO server_address:&server_address]) {
            // 获取到网络地址并导入Mesh数据
            UInt16 provisionAddress = [FDSMeshApi importMeshJson_Ex:meshDic provisionAddress:server_address];
            NSLog(@"provisionAddress ---> %d", provisionAddress);
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:@"数据无法导入，请重试！"];
            });
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 保存最新Mesh数据到本地
            self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
            [self.meshTool codingMeshData:self.meshTool.meshModel];
            
            [SVProgressHUD dismiss];
            [self presentTabViewController];
        });
        
        // 延时1秒后刷新状态
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [FDSMeshApi refreshWorkNormal];
        });
    });
}
- (void)replaceShareMeshJson{
    NSString *meshInfo = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"JSON_NAME_SHEAR" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
    self.meshTool.studioModel.meshJson = meshInfo;
}

@end
